import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFiles,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service';
import * as multer from 'multer';
import * as path from 'path';
import * as fs from 'fs';
// import { ConfigService } from '@nestjs/config';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('/files')
  /**
   * @description 控制器作用域的拦截器
   * 与 pipes 和 guards 一样，拦截器可以是控制器作用域的、方法作用域的或全局作用域的。
   */
  @UseInterceptors(
    /**
     * 该装饰器接受3个参数：fieldName，maxCount，options(可选的 MulterOptions 对象)
     */
    FilesInterceptor('files', undefined, {
      storage: multer.diskStorage({
        destination(_req, _file, cb) {
          // 根据环境配置path
          // const configService = new ConfigService();

          // const uploadPath =
          //   configService.get('NODE_ENV') === 'production'
          //     ? 'productionPath'
          //     : 'developmentPath';

          const uploadPath = path.join(__dirname, '..', '..', 'uploads');

          // 检查目标路径是否存在，如果不存在则创建
          if (!fs.existsSync(uploadPath)) {
            fs.mkdirSync(uploadPath, { recursive: true });
          }

          cb(null, uploadPath); // 目录设置
        },
        filename: (_req, file, cb) => {
          const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
          const fileExtension = path.extname(file.originalname);
          cb(null, `${uniqueSuffix}${fileExtension}`); // 设置文件名
        },
      }),
    }),
  )
  /**
   * @description 使用 @UploadedFiles() 装饰器从 request 中提取文件
   */
  async uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>) {
    const result = await Promise.all(
      files.map((file) => this.uploadService.uploadFile(file)),
    );
    return result;
  }

  @Post('/file')
  /**
   * @description 上传单个文件
   * @param file 文件
   *
   */
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    return await this.uploadService.uploadFile(file);
  }
}
